package showhow.simple.common;

import showhow.simple.common.enums.ErrorCode;
import lombok.Data;

import java.io.Serializable;
import java.util.Objects;

/**
 * 接口响应对象
 */
@Data
public class Result<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private int code;

    private String message;

    private T data;

    private boolean success;

    public static <T> Result<T> success() {
        return success(null);
    }

    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setCode(ErrorCode.SUCCESS.getCode());
        result.setMessage(ErrorCode.SUCCESS.getMsg());
        result.setData(data);
        result.setSuccess(true);
        return result;
    }

    public static <T> Result<T> failure(ErrorCode errorCode) {
        return failure(null, errorCode);
    }

    public static <T> Result<T> failure(T data, ErrorCode errorCode) {
        if (Objects.nonNull(errorCode)) {
            return failure(data, errorCode.getCode(), errorCode.getMsg());
        }
        return failure(data, ErrorCode.ERROR_CODE_OBJECT_IS_NULL.getCode(), ErrorCode.ERROR_CODE_OBJECT_IS_NULL.getMsg());
    }

    public static <T> Result<T> failure(int code, String message) {
        return failure(null, code, message);
    }

    public static <T> Result<T> failure(T data, int code, String message) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMessage(message);
        result.setData(data);
        result.setSuccess(false);
        return result;
    }
}
